package org.orr.budgetpro.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.orr.budgetpro.entities.Budget;
import org.orr.budgetpro.entities.ExpenseItem;
import org.orr.budgetpro.entities.IncomeItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class BudgetDAO {
	@Autowired
	private SessionFactory sessionFactory;

	public Budget getBudget(Integer budgetId) {
		return (Budget) sessionFactory.getCurrentSession().get(Budget.class,
				budgetId);
	}

	public Budget getBudgetByUserId(String userId) {
		Session session = sessionFactory.getCurrentSession();
		List budgetList = session
				.createQuery(
						"select b from Budget as b where b.user.userId = ?")
				.setString(0, userId).list();
		return (Budget) (budgetList.size() == 0 ? null : budgetList.get(0));
	}

	public void saveBudget(Budget budget) {
		Session session = sessionFactory.getCurrentSession();

		if (budget.getBudgetId() != null
				&& budgetIdExists(budget.getBudgetId())) {
			// If budget exists in database, update it
			session.merge(budget);
		} else {
			// Otherwise, budget doesn't exist, so save/insert it
			session.save(budget);
		}
	}

	public boolean budgetIdExists(Integer budgetId) {
		Session session = sessionFactory.getCurrentSession();
		List matchingBudgetIds = session
				.createQuery(
						"select budgetId from Budget as b where b.budgetId = ?")
				.setInteger(0, budgetId).list();
		return matchingBudgetIds.size() > 0;
	}

	public void deleteIncomeItem(Integer incomeItemId) {
		Session session = sessionFactory.getCurrentSession();
		IncomeItem item = (IncomeItem) session.get(IncomeItem.class,
				incomeItemId);

		Budget budget = item.getBudget();
		budget.getIncomeItems().remove(item);

		session.delete(item);
	}

	public void deleteExpenseItem(Integer expenseItemId) {
		Session session = sessionFactory.getCurrentSession();
		ExpenseItem item = (ExpenseItem) session.get(ExpenseItem.class,
				expenseItemId);

		Budget budget = item.getBudget();
		budget.getExpenseItems().remove(item);

		session.delete(item);
	}
}
